<template>
  <div id="houseInfo" class="p-2 addListBox">
    <div v-if="routerType == 'add'" style="margin: 20px 10px;font-weight: 600;font-size: 26px;display:flex;align-items: center;">添加房屋信息</div>
    <div v-else style="margin: 20px 10px;font-weight: 600;font-size: 26px;display:flex;align-items: center;">修改房屋信息</div>
    <el-card shadow="never">
      <el-table v-loading="loading" :data="houseInfoList">
        <el-table-column align="center">
          <template #header>
            <div>
              小区名称 <span style="color: #ff0000;">*</span> <br />
              <!-- <el-switch
                v-model="communitySwitchType"
                class="ml-2"
                inline-prompt
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                active-text="整体一致"
                inactive-text="逐个修改"
              /> -->
            </div>
          </template>
          <template #default="scope">
            <el-select
              class="slese"
              @visible-change="xmhandleVisibleChange"
              v-model="scope.row.projectId"
              placeholder="请选择小区"
              ref="selectRef"
              @change="communityChanged($event,scope.row)"
            >
              <el-option class="xmDropdown" v-for="item in communityOptions" :key="item.id" :label="item.projectName" :value="item.id" />
              <p class="el-select-dropdown__empty" v-show="loadingmore">加载中</p>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column align="center">
          <template #header>
            <div>房屋号 <span style="color: #ff0000;">*</span></div>
          </template>
          <template #default="scope">
            <el-input v-model="scope.row.houseNumber" placeholder="请输入房屋号" maxlength="10" />
          </template>
        </el-table-column>
        <el-table-column align="center" width="150px">
          <template #header>
            <div>
              房屋类别 <span style="color: #ff0000;">*</span> <br />
              <el-switch
                v-model="categorySwitchType"
                class="ml-2"
                inline-prompt
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                active-text="整体一致"
                inactive-text="逐个修改"
              />
            </div>
          </template>
          <template #default="scope">
            <el-select v-model="scope.row.houseCategory" placeholder="请选择类别" clearable @change="categoryChanged($event,scope.row)">
              <el-option v-for="dict in house_category" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200px">
          <template #header>
            <div>房屋实测面积 <span style="color: #ff0000;">*</span></div>
          </template>
          <template #default="scope">
            <el-input v-model="scope.row.houseArea" placeholder="请输入房屋实测面积" type="number" />
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template #header>
            <div>
              <div>是否交房</div>
              <el-switch
                v-model="isDeliveryHouseType"
                class="ml-2"
                inline-prompt
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                active-text="整体一致"
                inactive-text="逐个修改"
              />
            </div>
          </template>
          <template #default="scope">
            <el-select
              class="slese"
              v-model="scope.row.isDelivery"
              placeholder="请选择"
              ref="selectRef"
              @change="isDeliveryHouse($event,scope.row)"
            >
              <el-option v-for="item in is_delivery" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="收房时间" align="center">
          <template #default="scope">
            <el-date-picker
              clearable
              v-model="scope.row.houseReceiveDate"
              type="date"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择收房时间"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="装修申请时间" align="center">
          <template #default="scope">
            <el-date-picker
              clearable
              v-model="scope.row.houseDecorationDate"
              type="date"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择装修申请时间"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="入住情况" align="center" width="150px">
          <template #default="scope">
            <el-input v-model="scope.row.houseLiveInSituation" placeholder="请输入入住情况" />
          </template>
        </el-table-column>
        
        <el-table-column v-if="routerType == 'add'" label="操作" align="center" class-name="small-padding fixed-width" width="50px">
          <template #default="scope">
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="houseInfoList = houseInfoList.filter(item => item != scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div style="display: flex;justify-content: center;margin-top: 20px;">
      <el-button v-if="routerType == 'add'" type="primary" icon="Plus" @click="addLine">追加一条</el-button>
      <el-button v-if="routerType == 'add'" type="success" icon="Position" @click="handleQuery">提交全部</el-button>
      <el-button v-else type="success" icon="Position" @click="handleQuery">提交修改</el-button>
      <el-button @click="goBack">返 回</el-button>
    </div>
  </div>
</template>

<script setup name="AssetCataAdd" lang="ts">
import { listAssetLedger } from '@/api/business/assetLedger';
import { listProject } from '@/api/business/project';
import { getHouseInfo, addHouseInfo, updateHouseInfo } from '@/api/business/houseInfo';
import { HouseInfoVO } from '@/api/business/houseInfo/types';
import { ProjectQuery } from '@/api/business/project/types';

import { ref } from 'vue'

const tzOptions = ref()
const communityOptions = ref()

const router = useRoute()
const routerType = ref('add');
const communitySwitchType = ref(true);
const categorySwitchType = ref(true);
const isDeliveryHouseType = ref(true);

const houseInfoList = ref<HouseInfoVO[]>([]);
const listItem = {
  houseId: '',
  projectId: '',
  houseNumber: '',
  houseCategory: '',
  houseArea: '',
  houseReceiveDate: '',
  houseDecorationDate: '',
  houseLiveInSituation: '',
  remark: '',
}
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { house_category, is_delivery } = toRefs<any>(proxy?.useDict("house_category","is_delivery"));


const loading = ref(true);
const tzqueryParams = ref<ProjectQuery>({
  pageNum: 1,
  pageSize: 10,
})
const xmqueryParams = ref<ProjectQuery>({
  pageNum: 1,
  pageSize: 10,
  isExit: 0
})
const tztotal = ref(0);
const xmtotal = ref(0);
const errorLine = ref([])

// 追加一条
const addLine = () => {
  if(houseInfoList.value.length > 0) {
    communitySwitchType.value?listItem.projectId=houseInfoList.value[0].projectId:undefined
    categorySwitchType.value?listItem.houseCategory=houseInfoList.value[0].houseCategory:undefined
    isDeliveryHouseType.value?listItem.isDelivery=houseInfoList.value[0].isDelivery:undefined
  }
  houseInfoList.value.push(JSON.parse(JSON.stringify(listItem)))
}

const hasNoEmptyValues = () => {
  let flag = true
  // let checkNum = true
  // let arr = JSON.parse(JSON.stringify(houseInfoList.value)).reduce((result:any, obj:any)=>{
  //   let target = result.find((item:any) => {
  //     return item.propertyAssetLedgerId === obj.propertyAssetLedgerId;
  //   });
  //   if (target) {
  //     target.outboundQuantity = target.outboundQuantity + obj.outboundQuantity
  //   } else {
  //     result.push(obj);
  //   }
  //   return result;
  // }, [])
  const newArr=houseInfoList.value.map(item=>item.houseNumber);
  const isRepeat=newArr.some((item,index,arr)=>arr.indexOf(item)!=index);
  if(isRepeat){
    ElMessage.error('请勿填写重复的房屋号！')
    return false
  }
  for(let i=0;i<houseInfoList.value.length;i++) {
    if(routerType.value == 'edit') {
      if(houseInfoList.value[i].projectId == '' || houseInfoList.value[i].houseNumber == '' || houseInfoList.value[i].houseCategory == '' || houseInfoList.value[i].projectId == null || houseInfoList.value[i].houseNumber == null || houseInfoList.value[i].houseCategory == null){
        ElMessage.error('请将信息填写完成！')
        return false
      }else if(houseInfoList.value[i].houseArea <= 0 ||houseInfoList.value[i].houseArea > 999){
        ElMessage.error('请输入合理的实测面积！')
        return false
      }
      if (i==houseInfoList.value.length-1) {
        return true
      }
    }else {
      if(houseInfoList.value[i].projectId == '' || houseInfoList.value[i].houseNumber == '' || houseInfoList.value[i].houseCategory == '' || houseInfoList.value[i].projectId == null || houseInfoList.value[i].houseNumber == null || houseInfoList.value[i].houseCategory == null){
        ElMessage.error('请将信息填写完成！')
        return false
      }else if(houseInfoList.value[i].houseArea <= 0 ||houseInfoList.value[i].houseArea > 999){
        ElMessage.error('请输入合理的实测面积！')
        return false
      }
      if (i==houseInfoList.value.length-1) {
        return true
      }
    }
  }
  // houseInfoList.value.forEach((element,index) => {
  //   if(routerType.value == 'edit') {
  //     if(element.projectId == '' || element.houseNumber == '' || element.houseCategory == '' || element.projectId == null || element.houseNumber == null || element.houseCategory == null){
  //       flag?ElMessage.error('请将信息填写完成！'):''
  //       flag = false
  //     }else if(element.houseArea <= 0 ||element.houseArea > 999){
  //       flag?ElMessage.error('请输入合理的实测面积！'):''
  //       flag = false
  //     }else {
  //       flag = true
  //     }
  //   }else {
  //     if(element.projectId == '' || element.houseNumber == '' || element.houseCategory == '' || element.projectId == null || element.houseNumber == null || element.houseCategory == null){
  //       flag?ElMessage.error('请将信息填写完成！'):''
  //       flag = false
  //     }else if(element.houseArea <= 0 ||element.houseArea > 999){
  //       flag?ElMessage.error('请输入合理的实测面积！'):''
  //       flag = false
  //     }else {
  //       flag = true
  //     }
  //   }
  // })
  return flag
}


// 提交全部
const handleQuery = async () => {
  // errorLine.value = [0,2,5,7]
  // let houseCost = document.getElementById('houseInfo')
  // const errorList = houseCost?.getElementsByClassName('el-table__row')
  // errorLine.value.forEach(item => {
  //   errorList[item].className = 'el-table__row error-row'
  // })
  if(hasNoEmptyValues()) {
    if(routerType.value == 'edit') {
      await updateHouseInfo({'houseInfoListBo':houseInfoList.value}).then(() =>  {proxy?.$modal.msgSuccess("修改成功");});
      await goBack()
    }else {
      await addHouseInfo({'houseInfoListBo':houseInfoList.value}).then(() =>  {
        sessionStorage.setItem('houseInfo','')
        proxy?.$modal.msgSuccess("新增成功");});
      await goBack()
    }
  }
}

/** 返回 */
const goBack = () =>{
  const obj = { path: "/projectManagement/houseInfo"};
  proxy?.$tab.closeOpenPage(obj);
}

/** 查询小区管理列表 */
const getList = async () => {
  loading.value = true;
  const tz = await listAssetLedger(tzqueryParams.value);
  const xm = await listProject(xmqueryParams.value);
  tzOptions.value = tz.rows
  communityOptions.value = xm.rows
  // projectList.value = res.rows;
  tztotal.value = tz.total;
  xmtotal.value = xm.total;
  loading.value = false;
}

const handleVisibleChange = (visible: any) => {
  try {
    if (visible) {
      // 如果下拉框显示
      // let tzDropdown: any = document.querySelector('.el-select-dropdown__wrap')
      let tzDropdown: any = document.getElementsByClassName('tzDropdown')[0].parentElement.parentElement
      // 监听下拉框滚动事件
      tzDropdown.addEventListener('scroll', tzloadNextPage)
    } else {
      // 如果下拉框隐藏
      let tzDropdown: any = document.getElementsByClassName('tzDropdown')[0].parentElement.parentElement
      // 移除下拉框滚动事件监听
      tzDropdown.removeEventListener('scroll', tzloadNextPage)
    }
  } catch (error) {}
}
const xmhandleVisibleChange = (visible: any) => {
  try {
    if (visible) {
      // 如果下拉框显示
      let xmDropdown: any = document.getElementsByClassName('xmDropdown')[0].parentElement.parentElement
      // 监听下拉框滚动事件
      xmDropdown.addEventListener('scroll', xmloadNextPage)
    } else {
      // 如果下拉框隐藏
      let xmDropdown: any = document.getElementsByClassName('xmDropdown')[0].parentElement.parentElement
      // 移除下拉框滚动事件监听
      xmDropdown.removeEventListener('scroll', xmloadNextPage)
    }
  } catch (error) {}
}
const loadingmore = ref(false)
const loadingnomore = ref(false)
const tzloadNextPage = async () => {
  // let tzDropdown: any = document.querySelector('.el-select-dropdown__wrap');
  let tzDropdown: any = document.getElementsByClassName('tzDropdown')[0].parentElement.parentElement;
  // 判断下拉框是否触底
  if (tzDropdown.scrollTop + tzDropdown.clientHeight >= tzDropdown.scrollHeight - 2) {
    loadingnomore.value = false
    loadingmore.value = true
    if (tzOptions.value.length + 1 <= tztotal.value && loadingmore.value) {
      tzqueryParams.value.pageNum ++
      const res = await listAssetLedger(tzqueryParams.value)
      tzOptions.value.length + 1   <= tztotal.value?tzOptions.value.push(...res.rows):''
      loadingmore.value = false
    }else{
      loadingmore.value = false
    tzDropdown.removeEventListener('scroll', tzloadNextPage)
    loadingnomore.value = true
    }
  } else {
    loadingnomore.value = true
  }
}

const xmloadNextPage = async () => {
  // let xmDropdown: any = document.querySelector('.el-select-dropdown__wrap');
  let xmDropdown: any = document.getElementsByClassName('xmDropdown')[0].parentElement.parentElement;
  // 判断下拉框是否触底
  if (xmDropdown.scrollTop + xmDropdown.clientHeight >= xmDropdown.scrollHeight - 2) {
    loadingnomore.value = false
    loadingmore.value = true
    if (communityOptions.value.length + 1 <= xmtotal.value && loadingmore.value) {
      xmqueryParams.value.pageNum ++
      const res = await listProject(xmqueryParams.value)
      communityOptions.value.length + 1 <= xmtotal.value?communityOptions.value.push(...res.rows):''
      loadingmore.value = false
    }else{
      loadingmore.value = false
      xmDropdown.removeEventListener('scroll', xmloadNextPage)
      loadingnomore.value = true
    }
  } else {
    loadingnomore.value = true
  }
}


const communityChanged = async (id:string,row:any)=> {
  communityOptions.value.forEach((element) => {
    if(element.id == id) {
      row.projectId = element.id
      if(communitySwitchType.value) {
        houseInfoList.value.forEach(item => {
          item.projectId = row.projectId
        })
      }
    }
  });
}

const categoryChanged = async (row:any)=> {
  if(categorySwitchType.value) {
    houseInfoList.value.forEach(item => {
      item.houseCategory = row
    })
  }
}

// let filtermethodTimeInterval:any
// let filtermethodTimeIntervalflag = ref<boolean>(true)
// const filtermethod = (row) => {
//   loadingmore.value = true
//   loadingnomore.value = false
//   tzqueryParams.value.pageNum = 1
//   tzqueryParams.value.pageSize = 10
//   if(filtermethodTimeIntervalflag.value) {
//     filtermethodTimeInterval = setInterval(async() => {
//       filtermethodTimeIntervalflag.value = false
//       clearInterval(filtermethodTimeInterval)
//       const tz = await listAssetLedger({...tzqueryParams.value,name:row});
//       tzOptions.value = tz.rows
//       tztotal.value = tz.total;
//       loadingmore.value = false
//       loadingnomore.value = true
//       handleVisibleChange(true)
//     },500)
//   }else {
//     clearInterval(filtermethodTimeInterval)
//     filtermethodTimeInterval = setInterval(async() => {
//       clearInterval(filtermethodTimeInterval)
//       const tz = await listAssetLedger({...tzqueryParams.value,name:row});
//       tzOptions.value = tz.rows
//       tztotal.value = tz.total;
//       loadingmore.value = false
//       loadingnomore.value = true
//       handleVisibleChange(true)
//     },500)
//   }
// }

const isDeliveryHouse = (id:string,row:any) => {
  if(isDeliveryHouseType.value) {
    houseInfoList.value.forEach(item => {
        item.isDelivery = row.isDelivery
      })
    }
}

onMounted(async () => {
  await getList()
  if(router.query.type == 'edit') {
    routerType.value = router.query.type
    getHouseInfo(router.query.id).then(res => {
      houseInfoList.value = [res.data]
      // houseInfoList.value.forEach( element => {
      //   element.propertyAssetLedgerId = element.propertyAssetLedgerId
      // })
    })
  }else{
    addLine()
  }
})
</script>
<style>
.error-row {
  background:rgba(255, 0, 0, .3) !important;
}
</style>
